/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.rzt.cft.utils;


import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.dto.ResponseData;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     */
    public static ResponseData validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            String errMesage = "";
            Iterator iterator = constraintViolations.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation<Object> constraint = (ConstraintViolation<Object>) iterator.next();
                errMesage += constraint.getMessage() + ",";
            }
            errMesage = errMesage.substring(0, errMesage.length() - 1);
            return new ResponseData(ServiceStatus.PARAM_EXCEPTION, errMesage);
        }
        return null;
    }
}
